import { LOGIN_TOKEN } from '@/global/Constances'
import { localCache } from '@/utils/cache'
import { firstMenu, mapMenusToRotes } from '@/utils/map-menus'
import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: '/',
      redirect: '/main'
    },
    {
      path: '/login',
      component: () => import('@/views/login/Login.vue')
    },
    {
      path: '/main',
      name: 'main',
      component: () => import('@/views/main/Main.vue')
    },
    {
      path: '/:pathMatch(.*)',
      component: () => import('@/views/not-found/NotFound.vue')
    }
  ]
})
// 导航守卫
// 参数：to(跳转到的位置)，from(从哪里跳转过来)
// 返回值：返回值决定导航的路径（不返回或者返回undefined，默认跳转）
router.beforeEach((to) => {
  // 只有登录成功(token)，才能真正进入main页面
  const token = localCache.getCache(LOGIN_TOKEN)
  if (to.path === '/main' && !token) {
    return '/login'
  }
  if (to.path === '/main' && token) {
    return firstMenu.url
  }
})

// 重要：动态的添加路由,写在导航守卫里也可以,刷新能执行这些语句就行,
// 也可以在main.ts里面加,我其实加到了pinia的index.ts里
// if (localCache.getCache(LOGIN_TOKEN)) {
//   const routeItems = mapMenusToRotes(localCache.getCache('userMenus'))
//   // console.log(routeItems)
//   routeItems.forEach((item) => {
//     router.addRoute('main', item)
//   })
//   const date = new Date
// }

export default router
